package com.an.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.an.blog.admin.domain.BlogAlbum;
import com.an.blog.admin.domain.bo.BlogAlbumBo;
import com.an.blog.admin.domain.vo.BlogAlbumVo;
import com.an.blog.mapper.BlogAlbumMapper;
import com.an.blog.service.IBlogAlbumService;
import com.an.blog.service.IBlogPhotoService;
import com.an.blog.utils.ConvertUtil;
import com.an.blog.web.domain.vo.BlogAlbumWebVo;
import com.an.common.constant.BlogConstants;
import com.an.common.core.domain.BaseEntity;
import com.an.common.core.domain.PageQuery;
import com.an.common.core.page.TableDataInfo;
import com.an.common.exception.blog.BlogException;
import com.an.common.utils.StringUtils;
import com.an.system.domain.vo.SysOssVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 博客相册Service业务层处理
 *
 * @author Ann
 * @date 2023-05-08
 */
@RequiredArgsConstructor
@Service
public class BlogAlbumServiceImpl implements IBlogAlbumService {

    private final BlogAlbumMapper baseMapper;
    private final IBlogPhotoService photoService;

    /**
     * 查询博客相册
     */
    @Override
    public BlogAlbumVo queryById(Long albumId) {
        return baseMapper.selectVoById(albumId);
    }

    /**
     * 查询博客相册列表
     */
    @Override
    public TableDataInfo<BlogAlbumVo> queryPageList(BlogAlbumBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogAlbum> lqw = buildQueryWrapper(bo);
        Page<BlogAlbumVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BlogAlbumVo> records = result.getRecords();
        Map<Long, SysOssVo> sysOssVoMap = ConvertUtil
            .convert2OssIdSysOssMap(records, BlogAlbumVo::getAlbumImage);
        records.forEach(record -> {
            SysOssVo sysOssVo = sysOssVoMap.get(record.getAlbumImage());
            record.setAlbumImageUrl(sysOssVo != null ? sysOssVo.getUrl() : null);
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询博客相册列表
     */
    @Override
    public List<BlogAlbumVo> queryList(BlogAlbumBo bo) {
        LambdaQueryWrapper<BlogAlbum> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 建立查询包装
     *
     * @param bo 业务对象
     * @return {@link LambdaQueryWrapper }<{@link BlogAlbum }>
     * @author: Ann
     * @createDate: 2023/05/10 20:14:28
     * @version: 1.0.0
     */
    private LambdaQueryWrapper<BlogAlbum> buildQueryWrapper(BlogAlbumBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BlogAlbum> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getAlbumName()), BlogAlbum::getAlbumName, bo.getAlbumName());
        lqw.like(StringUtils.isNotBlank(bo.getAlbumDesc()), BlogAlbum::getAlbumDesc, bo.getAlbumDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BlogAlbum::getStatus, bo.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
            BaseEntity::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增博客相册
     */
    @Override
    public Boolean insertByBo(BlogAlbumBo bo) {
        BlogAlbum add = BeanUtil.toBean(bo, BlogAlbum.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAlbumId(add.getAlbumId());
        }
        return flag;
    }

    /**
     * 修改博客相册
     */
    @Override
    public Boolean updateByBo(BlogAlbumBo bo) {
        BlogAlbum update = BeanUtil.toBean(bo, BlogAlbum.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体
     * @author: Ann
     * @createDate: 2023/05/11 12:47:59
     * @version: 1.0.0
     */
    private void validEntityBeforeSave(BlogAlbum entity) {
        if (StringUtils.isNotEmpty(entity.getAlbumName()) && !checkAlbumNameUnique(entity)) {
            throw new BlogException("blog.album.add.not.unique");
        }
    }


    /**
     * 检查相册名字独特
     *
     * @param entity 实体
     * @return boolean
     * @author: Ann
     * @createDate: 2023/05/11 12:49:06
     * @version: 1.0.0
     */
    private boolean checkAlbumNameUnique(BlogAlbum entity) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<BlogAlbum>()
            .eq(BlogAlbum::getAlbumName, entity.getAlbumName())
            .ne(ObjectUtil.isNotNull(entity.getAlbumId()), BlogAlbum::getAlbumId, entity.getAlbumId()));
        return !exist;
    }

    /**
     * 批量删除博客相册
     *
     * @param ids     id
     * @param isValid 是有效
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/05/11 12:33:28
     * @version: 1.0.0
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            if (photoService.exist(ids)) {
                throw new BlogException("blog.album.delete.error");
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 更新相册状态
     *
     * @param bo 业务对象
     * @return int
     * @author: Ann
     * @createDate: 2023/05/10 20:42:12
     * @version: 1.0.0
     */
    @Override
    public int updateAlbumStatus(BlogAlbumBo bo) {
        BlogAlbum blogAlbum = BeanUtil.toBean(bo, BlogAlbum.class);
        return baseMapper.updateById(blogAlbum);
    }

    /**
     * 查询通过id列表
     *
     * @param albumIds 相册id
     * @return {@link List }<{@link BlogAlbumVo }>
     * @author: Ann
     * @createDate: 2023/05/10 21:24:28
     * @version: 1.0.0
     */
    @Override
    public List<BlogAlbumVo> queryListByIds(Collection<Long> albumIds) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<BlogAlbum>()
            .select(BlogAlbum::getAlbumId, BlogAlbum::getAlbumName)
            .in(CollUtil.isNotEmpty(albumIds), BlogAlbum::getAlbumId, albumIds));
    }

    /**
     * 查询页面列表
     *
     * @param pageQuery 页面查询
     * @return {@link TableDataInfo }<{@link BlogAlbumWebVo }>
     * @author: Ann
     * @createDate: 2023/06/26 10:34:56
     * @version: 1.0.0
     */
    @Override
    public TableDataInfo<BlogAlbumWebVo> queryWebPageList(PageQuery pageQuery) {
        Page<BlogAlbum> result = baseMapper.selectPage(pageQuery.build(), new LambdaQueryWrapper<BlogAlbum>()
            .eq(BlogAlbum::getStatus, BlogConstants.NORMAL));
        List<BlogAlbum> records = result.getRecords();
        long total = result.getTotal();
        List<BlogAlbumWebVo> blogAlbumWebVos = BeanUtil.copyToList(records, BlogAlbumWebVo.class);
        return TableDataInfo.build(blogAlbumWebVos, total);
    }
}
